package com.loong.storm;

import org.apache.storm.trident.TridentTopology;
import org.apache.storm.trident.operation.BaseFunction;
import org.apache.storm.trident.operation.TridentCollector;
import org.apache.storm.trident.operation.builtin.Count;
import org.apache.storm.trident.testing.FixedBatchSpout;
import org.apache.storm.trident.testing.MemoryMapState;
import org.apache.storm.trident.tuple.TridentTuple;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Values;
import org.junit.Test;

/**
 * 三叉戟
 * Created by 梁浩峰 on 2016/9/7 16:50.
 */
public class ThreadChaJI {

    @Test
    public void dataSource(){
        FixedBatchSpout spout = new FixedBatchSpout(new Fields("sentence"), 3, new Values("the cow jumped over the moon"), new Values("the man went to the store and bought some candy"),
                new Values("four score and seven years ago"),
                new Values("how many apples can you eat"));

        spout.setCycle(true);


        TridentTopology topology = new TridentTopology();
        topology.newStream("spout1",spout)
                .each(new Fields("sentence"),new Split(),new Fields("word"))
                .groupBy(new Fields("word"))
                .persistentAggregate(new MemoryMapState.Factory(),new Count(),new Fields("count"))
                .parallelismHint(6);
    }


    public class Split extends BaseFunction{

        public void execute(TridentTuple tuple, TridentCollector collector) {
            String sentence = tuple.getString(0);
            for (String word:sentence.split(" ")
                 ) {
                collector.emit(new Values(word));
            }
        }
    }
}
